<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/10/31
 * Time: 14:38
 */

namespace app\common\model;

use app\common\lib\astrolog\Acg;
use app\common\lib\exception\ApiException;
use Exception;
use think\Cache;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Log as Log;

class FateCity extends Base
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_fate_city_user';
    public static $cacheKey = 'map:fate_city2:';//命运之城缓存key
    public static $scoreCity = 'map:city_score1:';//城市排行缓存key

    /**
     * @param $map
     * @return array|bool|mixed
     * @throws ApiException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserFateCitys($map)
    {
        $result = false;
        if ($this->cache_on >= 1)
        {
            $result = Cache::get(self::$cacheKey . $map['rid']);
        }
        if (empty($result))
        {
            $fate_city = config('map');
            $fate_city_name = $fate_city['fate_city_name'];
            $fate_city_loc = $fate_city['fate_city_loc'];
            $fate_city_des = $fate_city['fate_city_title'];// 命运之城提示窗信息
            $result = [];
            // 当前无缓存，先查库（是否计算过）
            try
            {
                $data = $this->table('wechat_backup_07_18_14_43_00.app_fate_city_user')
                    ->alias('fcu')
                    ->join('wechat_backup_07_18_14_43_00.app_map m', 'fcu.mid=m.id')
                    ->field('fcu.fcid,m.id,m.longitude,m.latitude')
                    ->where(['fcu.uid' => $map['uid'], 'fcu.rid' => $map['rid']])
                    ->selectOrFail();
                foreach ($data as $d)
                {
                    // key 为经纬度id 即城市id
                    if (isset($result[$d['id']]['name']))
                    {
                        if (strpos($result[$d['id']]['name'], $fate_city_name[$d['fcid']]) === false)
                        {
                            $result[$d['id']]['name'] .= '、' . $fate_city_name[$d['fcid']];
                        }
                        $strlen = mb_strlen($result[$d['id']]['name']);
                        if ($strlen === 9)
                        {
                            $result[$d['id']]['icon'] = $fate_city['fate_city'][10];
                            $result[$d['id']]['loc_icon'] = $fate_city_loc[10];
                            $result[$d['id']]['description'] = $fate_city_des[10];
                        }
                    } else
                    {
                        $result[$d['id']]['name'] = $fate_city_name[$d['fcid']];
                        $result[$d['id']]['icon'] = $fate_city['fate_city'][$d['fcid']];
                        $result[$d['id']]['loc_icon'] = $fate_city_loc[$d['fcid']];
                        $result[$d['id']]['description'] = $fate_city_des[$d['fcid']];
                        $result[$d['id']]['longitude'] = $d['longitude'];
                        $result[$d['id']]['latitude'] = $d['latitude'];
                    }
                }

                // 首次运算命运之城数据，计算后入库
            }
            catch (Exception $e)
            {
                Log::write($map['uid'] . '数据库获取命运之城失败：' . $e->getMessage(), 'error', true);
                //设置幸运之城按钮显示为计算中
                Cache::set($map['uid'] . ':' . $map['rid'] . '_acg_logic_status', 1);
                // 一二三级城市配置文件合并统一
                $citys = array_slice(config('city.city_list'), 0, 2);

                $map['fate'] = true;
                $score = [];
                if (!empty($citys))
                {
                    foreach ($citys as $k => $city)
                    {
                        $map['point_longitude'] = $city['lon'];
                        $map['point_latitude'] = $city['lat'];
                        $score[$k] = (new Acg())->getRecommendedInfo($map);
                    }
                }

                $list = $result = $fates = [];
                foreach ($score as $i => $c)
                {
                    foreach ($c as $j => $s)
                    {
                        $list[$j][$i] = $s;
                    }
                }

                foreach ($list as $fate => $l)
                {
                    $max = max($l);

                    if ($max <= 0)
                    {
                        continue;
                    }

                    $fate_name = $fate_city['fate_city_name'][$fate];
                    foreach ($l as $key => $m)
                    {
                        // 获取最大值城市 key
                        if ($m == $max)
                        {
                            $lon_lat = $citys[$key];// 命运之城城市经纬度
                            if (isset($result[$key]['name']))
                            {
                                // 当前城市属于多个命运之城
                                if (strpos($result[$key]['name'], $fate_name) === false)
                                {
                                    $result[$key]['name'] .= '、' . $fate_name;
                                }
                                $result[$key]['icon'] = $fate_city['fate_city'][10];
                                $result[$key]['loc_icon'] = $fate_city['fate_city_loc'][10];
                                $result[$key]['description'] = $fate_city['fate_city_title'][10];
                            } else
                            {
                                // 第一条
                                $result[$key] = [
                                    'icon' => $fate_city['fate_city'][$fate],
                                    'loc_icon' => $fate_city['fate_city_loc'][$fate],
                                    'name' => $fate_name,
                                    'description' => $fate_city['fate_city_title'][$fate],
                                    'longitude' => $lon_lat['lon'],
                                    'latitude' => $lon_lat['lat']
                                ];
                            }
                            $fates[] = [
                                'id' => $fate,
                                'uid' => $map['uid'],
                                'rid' => $map['rid'],
                                'longitude' => $lon_lat['lon'],
                                'latitude' => $lon_lat['lat']
                            ];
                        }
                    }
                }
                $this->saveFateCity($fates);// 保存命运之城入库
                // 获取当前最新的逻辑版本号
                $SystemLogicModel = new SystemLogicVersion();
                $logicVersionData = [
                    'rid' => $map['rid'],
                    'type' => 1,
                ];
                $logic_lastes = $SystemLogicModel->getVersion(['type' => $logicVersionData['type']]);

                $logicVersionData['version'] = $logic_lastes['version'] ?? 0;
                //获取当前档案逻辑版本号
                $AppLogicModel = new AppLogicVersion();
                $logic_user = $AppLogicModel->getVersion([
                    'rid' => $map['rid'],
                    'type' => $logicVersionData['type'],
                ]);
                // 新增
                if (!$logic_user)
                {
                    $AppLogicModel->addVersion($logicVersionData);
                } //更新逻辑版本
                elseif ($logicVersionData['version'] && $logic_user < $logicVersionData['version'])
                {
                    $AppLogicModel->updateVersion($logicVersionData);
                }
                //将更新状态改为无需更新
                Cache::rm($map['uid'] . ':' . $map['rid'] . '_acg_logic_status');
            }
        }

        if (!empty($result))
        {
            foreach ($result as $k => $r)
            {
                $fate_citys = array_filter(explode('、', $r['name']));

                $fate_city_count = count($fate_citys);

                if ($fate_city_count > 1)
                {


                    if ($fate_city_count == 2)
                    {
                        $replace_str = '既是你的' . $fate_citys[0] . '，又是你的' . $fate_citys[1];

                        // 这座城市对你来说可谓祥云笼罩，大吉大利，既是你的XX之城，又是你的XX之城。想知道它会给你带来哪些具体好处，可点击进入城市详情页面查看。
                        $result[$k]['description'] = str_replace('[city]', $replace_str, $r['description']);
                    } else
                    {
                        $replace_str = '分别是你的';

                        for ($i = 0; $i < $fate_city_count - 1; $i++)
                        {
                            $replace_str .= $fate_citys[$i] . '、';
                        }

                        $replace_str = mb_substr($replace_str, 0, -1);

                        $replace_str .= '和' . $fate_citys[$fate_city_count - 1];

                        // 这座城市对你来说可谓祥云笼罩，大吉大利，分别是你的XX之城、XX之城、XX之城和XX之城。想知道它会给你带来哪些具体好处，可点击进入城市详情页面查看。
                        $result[$k]['description'] = str_replace('[city]', $replace_str, $r['description']);
                    }
                }
            }
            $result = array_values($result);
        }

        Cache::set(self::$cacheKey . $map['rid'], $result, 86400 * 3);
        return $result;
    }

    /**
     * @param array $data
     * @return bool
     */
    public function saveFateCity($data = []): bool
    {
        if (!empty($data))
        {
            $rid = null;
            $inserts = [];
            $uid = null;
            // 一二三级城市配置文件合并统一
            $citys = config('city.city_list');

            foreach ($data as $f)
            {
                foreach ($citys as $i => $c)
                {
                    if ($f['longitude'] == $c['lon'] && $f['latitude'] == $c['lat'])
                    {
                        if ($rid === null)
                        {
                            $rid = $f['rid'];
                        }
                        if ($uid === null)
                        {
                            $uid = $f['uid'];
                        }

                        $inserts[] = ['mid' => $c['id'], 'fcid' => $f['id'], 'uid' => $f['uid'], 'rid' => $f['rid']];
                    }
                }
            }
            if (!empty($inserts))
            {
                try
                {
                    //删除档案之前的命运之城的数据
                    $this->removeFateCity(['uid' => $uid, 'rid' => $rid]);
                    $this->insertAll($inserts);
                }
                catch (Exception $e)
                {
                    Log::write('命运之城写入失败：' . $e->getMessage(), 'error', true);
                }
            }
        }
        return true;
    }

    /**
     * 删除用户已生成的命运之城
     * @param array $map
     * uid int must 用户id
     * rid int must 档案id
     * @return bool
     */
    public function removeFateCity($map = []): bool
    {
        if (isset($map['uid'], $map['rid']) && !empty($map) && $map['uid'] && $map['rid'])
        {
            try
            {
                // 先删除当前档案的命运之城
                $this->where($map)->delete();

                Cache::rm(self::$cacheKey . $map['rid']);
            }
            catch (Exception $e)
            {
                Log::write('命运之城删除失败：' . $e->getMessage(), 'error', true);
            }
        }

        return true;
    }
}
